<template>
    <div class="article-search">
        <el-form :inline="true" :model="queryInfo" class="form-inline">
            <el-form-item label="文章名称">
            <el-input v-model="queryInfo.articleName" placeholder="请输入文章名称" style="width: 170px;" clearable />
            </el-form-item>
            <el-form-item label="咨询师">
            <el-input v-model="queryInfo.consultId" placeholder="请输入咨询师名称" style="width: 170px;" clearable />
            </el-form-item>
            <el-form-item label="阅读量">
              <el-input v-model="queryInfo.readQuantity" placeholder="请输入最小阅读量" style="width: 170px;" clearable />
            </el-form-item>
            <el-form-item label="收藏量">
              <el-input v-model="queryInfo.collects" placeholder="请输入最小阅读量" style="width: 170px; margin-left: 15px;" clearable />
            </el-form-item>
            <el-form-item>
            <el-button type="primary" @click="getList">搜索</el-button>
            <el-button icon="Delete" @click="reset()">重置</el-button>
            <el-button type="primary" icon="CirclePlusFilled" @click="addForm()">添加</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="article-table">
        <el-table :data="tableData" style="width: 1200px; height: 500px; overflow-x: auto !important; margin: 0 auto;">
            <el-table-column label="序号" width="50">
              <template #default="{ $index }">
                {{ $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="articleName" label="文章名称" width="150"/>
            <el-table-column prop="articleIntroduce" label="简介" width="150">
              <template #default="scope">
                  <el-button link type="primary" v-if="scope.row.articleIntroduce!=null" @click="details(1,scope.row)">
                      <el-icon><Help /></el-icon>
                      <span>详情</span>
                  </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="consult.name"  label="咨询师">
              <template #default="scope"> 
                <!-- {{ scope.row.consultId }} -->
                {{ consultList[scope.row.consultId] }}
              </template> 
            </el-table-column>
            <el-table-column prop="tabularChart" label="图片" width="150">
                <template #default="scope">
                    <!-- {{ url }} -->
                    <!-- {{ scope.row.tabularChart }} -->
                    <el-image  v-if="scope.row.tabularChart" :src="url + scope.row.tabularChart" alt="" style="width: 100px; height: 100px;"/>
                </template>
            </el-table-column>
            <el-table-column prop="readQuantity" label="阅读量" width="100"/>
            <el-table-column prop="details" label="内容" width="100">
              <template #default="scope">
                  <el-button link type="primary" v-if="scope.row.details!=null" @click="details(2,scope.row)">
                      <el-icon><Help /></el-icon>
                      <span>详情</span>
                  </el-button>
              </template>
            </el-table-column>

            <el-table-column prop="collects" label="收藏量" width="100"/>
            <el-table-column prop="articleType.name"  label="分类">
              <template #default="scope">
                <!-- {{ scope.row.typeId }} -->
                {{ typeList[scope.row.typeId] }}
              </template> 
            </el-table-column>

            <el-table-column prop="createTime" label="创建时间" width="150"/>
            <el-table-column fixed="right" label="操作">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="modify(scope.row)">
                    修改
                    </el-button><br/>
                    <el-button link type="primary" icon="Delete" @click="del(scope.$index)">
                    删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
          style="width: 1200px; margin: 20px auto 0 auto;"
          v-model:current-page="queryInfo.pageNum"
          v-model:page-size="queryInfo.pageSize"
          :page-sizes="[3, 5, 10, 20]"
          size="default"
          background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
    </div>

    <el-dialog 
      v-model="addFormVisible" 
      :title="dialogType==0?'添加':'修改'" 
      width="500"
      @close="cancel"
      >
        <el-form :model="articleInfor">
        <el-form-item label="文章名称">
            <el-input v-model="articleInfor.articleName" autocomplete="off" placeholder="请输入文章名" />
        </el-form-item>
        <el-form-item label="文章简介">
            <el-input v-model="articleInfor.articleIntroduce" autocomplete="off" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="咨询师名">
          <el-select v-model="articleInfor.consultId" placeholder="请选择咨询师">
              <el-option
                v-for="item in consults"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              /> 
          </el-select> 
        </el-form-item>

        <el-form-item label="类型">
          <!-- {{ types }} -->
          <el-select v-model="articleInfor.typeId" placeholder="请选择类型" style="margin-left: 30px;">
              <el-option
                v-for="item in types"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              /> 
          </el-select> 
        </el-form-item>


        <el-form-item label="阅读量">
          <el-input v-model="articleInfor.readQuantity" style="margin-left: 15px;"  autocomplete="off" placeholder="请输入阅读量" />
        </el-form-item>

        <el-form-item label="图片" :label-width="formLabelWidth">
            <el-upload
              style="margin-left: 30px;"
              v-model:file-list="fileList"
              class="avatar-uploader"
              list-type="picture-card"
              action="http://localhost/file/upload"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="!fileList" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item label="收藏量" >
            <el-input v-model="articleInfor.collects" style="margin-left: 15px;" autocomplete="off" placeholder="请输入收藏量"/>
        </el-form-item>

        <el-form-item label="创建时间">
            <el-date-picker
                v-model="articleInfor.createTime"
                type="date"
                placeholder="选择时间"
                clearable
            />
            </el-form-item>
        </el-form>
        <template #footer>
        <div class="dialog-footer">
            <el-button @click="cancel2">取消</el-button>
            <el-button type="primary" @click="addOrModifyInfor()">
              {{ dialogType==0?'添加':'修改' }}
            </el-button>
        </div>
        </template>
    </el-dialog>


    <el-dialog v-model="detailsVisible" :title="detailsInfor.content!=null?'内容':'简介'" :width="detailsInfor.content!=null?'1000px':'500px'" 
            @close="clearInfor()">
                <quill-editor v-if="detailsInfor.content!=null" v-model:value="detailsInfor.content" />
                <quill-editor v-if="detailsInfor.articleIntroduce!=null" v-model:value="detailsInfor.articleIntroduce" />
                <div>
                  <button type="success" @click="editDetails()" v-show="detailsInfor.content!=null" style="background: #409eff; width: 100px; height: 30px; color: white; margin: 10px; border: none; border-radius: 5px;">修改</button>
                </div>
    </el-dialog>


</template>

<script setup>
import {ref,onMounted } from 'vue'
import {ElMessage , ElMessageBox } from 'element-plus'
import QuillEditor from '@/components/QuillEditor.vue';
import axios from 'axios'
const addFormVisible = ref(false)


const totalNum = ref(0);

const dialogType = ref(0);

const url = ref("http://localhost/file/downLoad?fileName=");

const delUrl = ref("");

const rowId = ref(0);

const typeList = ref([]);
const consultList = ref([]);

// 定义一个方法当页面加载后立马执行的代码
onMounted(()=>{
    // console.log('onMounted');
    getList();
})


const detailsVisible = ref(false);
const detailsInfor = ref({
    articleIntroduce: null,
    content: null
})


function editDetails() {
  // console.log(rowId.value);
  // console.log(detailsInfor.value); 

  articleInfor.value.id = rowId.value;
  articleInfor.value.details = detailsInfor.value.content;

  //console.log(articleInfor.value);
  dialogType.value=1;
  addOrModifyInfor();
  


}

function clearInfor() {
    detailsInfor.value.articleIntroduce=null;
    detailsInfor.value.content=null;
}

function details(n,row) {
  detailsVisible.value = true;
  //console.log(n);
  //console.log(row); 
  if(n==1){
    detailsInfor.value.articleIntroduce=row.articleIntroduce;
  }else{
    rowId.value = row.id;
    detailsInfor.value.content=row.details;
  }
}


// 定义一个全局的查询参数变量
const queryInfo = ref({
    pageNum:'',
    pageSize: 5,
    name:'',
    author:'',
    read: null,
    createTime: null,
})


//重置并刷新
function reset() {
    queryInfo.value.name = '';
    queryInfo.value.author = '';
    queryInfo.value.read = null;
    queryInfo.value.createTime = null;
    getList();
}

// 定义一个方法，当页码发生变化时，调用后端接口，获取文章列表
const handleCurrentChange = (val)=>{
    queryInfo.value.pageNum = val;
    getList();
}

// 定义一个方法，当每页显示的条数发生变化时，调用后端接口，获取文章列表
const handleSizeChange = (val)=>{
    queryInfo.value.pageSize = val;
    queryInfo.value.pageNum = 1;
    getList(); 
}

const consults = ref([]);

const types = ref([]);

const getInforList = ()=>{
  axios.get('/type/selectAllReally')
  .then(resp=>{
    let result = resp.data; 
    //console.log(result.data);
    
    if(result.code==1){
      types.value = result.data;
      for(let i=0;i<result.data.length;i++){
        typeList.value[result.data[i].id] = result.data[i].name;
      }   
      
      //console.log(111,typeList.value);
      
    }else{
      console.log('获取文章类型列表失败');
    }
  })

  axios.get('/consult/findAllReally')
  .then(resp=>{
    let result = resp.data; 
    //console.log(result.data);
    
    if(result.code==1){
      consults.value = result.data;
      for(let i=0;i<result.data.length;i++){
        consultList.value[result.data[i].id] = result.data[i].name;
      }  
      //console.log(222,consultList.value);
    }else{
      console.log('咨询师获取失败');
    }
  })
}



//定义一个方法，来动态的调用后端接口，获取文章列表
const getList = ()=>{
    // 使用axios调用后端接口获取数据
    axios.get('/article/selectAll',{
        params: queryInfo.value
    })
    .then(resp=>{
        //console.log(resp.data);
        let result = resp.data;
        if(result.code==1){
            tableData.value = result.data.list;  
            //console.log(result.data.list);
            
            //console.log(tableData.value);
            
            totalNum.value = result.data.total;
            getInforList();
            //console.log('获取文章列表成功');      
        }else{
            console.log('获取文章列表失败')
        }
    })
    
}


const tableData = ref([
  {
    id: 0,
    articleName: '',
    articleIntroduce: '',
    consultId:0,
    tabularChart:'', //图片
    details:'',
    readQuantity: 0,
    collects: 0,
    consult:{
      id:0,
      name:''
    },
    typeId:0,
    createTime: '',
    articleType:{
      id:0,
      name:''
    }
  }
])

const articleInfor = ref(
  {
    id: 0,
    articleName: '',
    articleIntroduce: '',
    consultId:'',
    consult:{
      id:0,
      name:'' 
    },
    tabularChart:'', //图片
    details:'',
    readQuantity: '',
    collects: '',
    typeId: '',
    createTime: '',
    articleType:{
      id:0,
      name:''
    }
  }
)

const fileList = ref([]);
const imageUrl=ref('');
// 图片上传
const handleAvatarSuccess = (response,
uploadFile)  => {

  imageUrl.value = URL.createObjectURL(uploadFile.raw);

  
  delUrl.value = response.data;
  articleInfor.value.tabularChart = response.data;

}



function addForm() {
  dialogType.value = 0;
  articleInfor.value.name = '';
  articleInfor.value.consultId = '';
  articleInfor.value.typeId = '';
  articleInfor.value.introduce = '';
  articleInfor.value.read = '';
  articleInfor.value.createTime = '';
  articleInfor.value.tabularChart = '';
  addFormVisible.value=true;
}

function modify(row) {
  dialogType.value = 1;
  articleInfor.value = row;
  //console.log(2222,articleInfor.value);
  
  addFormVisible.value=true;
  //console.log(articleInfor.value.tabularChart);
  
  // 把图片的名称和路径放入到fileList中
  if(articleInfor.value.tabularChart==''||articleInfor.value.tabularChart==null){
    fileList.value = [];
  }else{
    fileList.value = [{
      name: articleInfor.value.tabularChart,
      url: url.value + articleInfor.value.tabularChart
    }];
  }
}



function addOrModifyInfor() {
  console.log(1111,articleInfor.value);
  
  if(dialogType.value==0){
    axios.post('/article/addArticle',articleInfor.value) 
    .then(resp=>{
        // console.log(resp.data)
        let result =  resp.data;  // resp是promise对象，.data返回我们自己的标准R
        if(result.code==1){
          ElMessage({
              message: '添加成功！',
              type:'success',
          });          
            // 重新获取列表
            getList(); 
        } else{
          ElMessage({
              message: '添加失败！',
              type:'warning',
          });   
            console.log('添加文章失败')
        }
    })
  }else{
    axios.put('/article/updateA',articleInfor.value) 
   .then(resp=>{
        // console.log(resp.data)
        let result =  resp.data;  // resp是promise对象，.data返回我们自己的标准R
        if(result.code==1){
          ElMessage({
              message: '修改成功！',
              type:'success',
          })
            // 重新获取列表
            getList(); 
        } else{
          ElMessage({
              message: '修改失败！',
              type:'warning',
          })
            console.log('修改文章失败') 
        }
   })
  }
  fileList.value = [];
  articleInfor.value = {
    id: 0,
    articleName: '',
    articleIntroduce: '',
    consultId:'',
    consult:{
      id:0,
      name:''
    },
    tabularChart:'', //图片
    details:'',
    readQuantity: '',
    collects: '',
    typeId: '',
    createTime: '',
    articleType:{
      id:0,
      name:''
    }
  }
  addFormVisible.value=false;
}

function delImgInPan(){
  console.log(delUrl.value);
  axios.delete('http://localhost/file/delete',{params: {fileName: delUrl.value}})
}

function cancel2() {
  delImgInPan();  
  addFormVisible.value=false;
}

function cancel() {
  getList();
  articleInfor.value = {
    id: 0,
    articleName: '',
    articleIntroduce: '',
    consultId:'',
    consult:{
      id:0,
      name:''
    },
    tabularChart:'', //图片
    details:'',
    readQuantity: '',
    collects: '',
    typeId: '',
    createTime: '',
    articleType:{
      id:0,
      name:''
    }
  }
  fileList.value = [];
  imageUrl.value = '';
}

function del(n) {
  let id = tableData.value[n].id;

  delUrl.value = tableData.value[n].imageUrl;
  ElMessageBox.confirm(
    '你确定要删除吗？',
    '确定',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      // tableData.value.splice(n,1);
      // for(let i =0; i<tableData.value.length; i++){
      //   tableData.value[i].num = i+1;
      // }
      // ElMessage({
      //   type: 'success',
      //   message: '删除成功！',
      // })
      // 调用后端接口删除
      axios.delete('/article/'+id)
        .then(resp=>{
            // console.log(resp.data)
            let result =  resp.data;  // resp是promise对象，.data返回我们自己的标准R 
            if(result.code==1){
              delImgInPan();
              // 重新获取列表
              getList(); 
              ElMessage({
                  message: '删除成功！',
                  type: 'success',
              })
            }else{
              ElMessage({
                  message: '删除失败！',
                  type: 'warning',
              })
            }
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

</script>

<style scoped>
.article-search{ width: 800px; margin: 30px;}
.article-table{ z-index: 0;position: relative;}

.avatar-uploader .el-upload {
  border: 1px dashed black;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 160px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 160px;
  height: 160px;
  display: block;
}

</style>